package com.helloworld.chat.service.impl;

import com.helloworld.chat.cache.CacheManager;
import com.helloworld.chat.cache.UserCache;
import com.helloworld.chat.cache.UserCacheModel;
import com.helloworld.chat.dao.GroupDao;
import com.helloworld.chat.dao.UserDao;
import com.helloworld.chat.entity.Group;
import com.helloworld.chat.entity.User;
import com.helloworld.chat.service.UserService;
import com.helloworld.chat.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by xdzy on 2017/6/28.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService{
    private UserDao userDao;
    private GroupDao groupDao;
    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    @Autowired
    public void setGroupDao(GroupDao groupDao) {
        this.groupDao = groupDao;
    }
    @Override
    public void register(User user) {
        String newPwd= MD5Util.makeMD5Code(user.getPassword());
        user.setPassword(newPwd);
        user.setNickName(user.getUsername());
        user.setHeadImg("system_man.jpg");
        userDao.register(user);
        Group group=new Group();
        group.setGroupName("默认分组");
        group.setUid(user.getUid());
        groupDao.addGroup(group);
        UserCacheModel ucm;
        ucm=new UserCacheModel();
        ucm.setChating("");
        ucm.setStatus("0");
        CacheManager.getUserCache().addUser(user.getUid()+"",ucm);
    }

    @Override
    @Transactional(readOnly = true)
    public User login(User user) {
        User dbUser=userDao.getUser(user.getUsername());
        user.setPassword(MD5Util.makeMD5Code(user.getPassword()));
        if(dbUser==null||!(dbUser.getPassword().equals(user.getPassword()))){
            return null;
        }
        return dbUser;
    }

    @Override
    public User getUser(int id) {
        return userDao.getUser(id);
    }

    @Override
    public User findByUserName(String username) {
        // TODO Auto-generated method stub
        return userDao.findByUserName(username);
    }

    @Override
    public void update(User user) {
        // TODO Auto-generated method stub
        userDao.update(user);
    }

    @Override
    public User findById(int uid) {
        // TODO Auto-generated method stub

        return userDao.findById(uid);
    }

    @Override
    public UserCache getUserCache() {
        List<User> list=userDao.getUserList();
        UserCache userCache=new UserCache();
        list.forEach((user)->{
            UserCacheModel ucm;
            ucm=new UserCacheModel();
            ucm.setChating("");
            ucm.setStatus("0");
            userCache.addUser(user.getUid()+"",ucm);
        });
        return userCache;
    }
}
